package com.woniuxy.oldmanapi.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.oldmanapi.cvo.CareprojectVo;
import com.woniuxy.oldmanapi.entity.Careproject;
import com.woniuxy.oldmanapi.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CareProjectService {
    @Autowired
    CaretypeMapper caretypeMapper;
    @Autowired
    CareprojectMapper careprojectMapper;
    @Autowired
    CareCareprojectMapper careCareprojectMapper;
    @Autowired
    CareMapper careMapper;
    @Autowired
    OlderMapper olderMapper;


    public PageInfo<CareprojectVo> findCareproject(int caretypeId, String pname, int size, int now) {
        PageHelper.startPage(now,size);
        List<CareprojectVo> list=careprojectMapper.selectByCons(caretypeId,pname);
        return  new PageInfo<>(list);
    }

    public void addcareproject(Careproject careproject) {
        careprojectMapper.insert(careproject);
    }

    public void modifyCareproject(Careproject careproject) {
        careprojectMapper.updateByPrimaryKey(careproject);
    }

    //删除
    @Transactional
    public void removeCareproject(int id) {
        //查询出有此服务项目的护理级别id--是否有护理级别-->查询使用者
        List<Integer> careIds=careCareprojectMapper.selectByCareprojectId(id);
        if(careIds.size()>0){
            List<Integer> olders = olderMapper.selectByCareIds(careIds);
            if(olders.size()>0){
                throw  new RuntimeException("此护理项目有长者正接受服务，不可删除！");
            }else {
                //==1.删除服务项目；3.删除护理级别；4.删除护理级别明细（根据护理级别id删除，如果根据项目id没删除完护理级别明细）
                careprojectMapper.deleteByPrimaryKey(id);
                careMapper.removeBeachByIds(careIds);
                careCareprojectMapper.removeBeachByCareids(careIds);

            }
        }else {
            //没有护理级别使用，删除项目
            careprojectMapper.deleteByPrimaryKey(id);
        }
    }
}
